package com.hangxintong.common;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hangxintong.common.exception.SystemException;
import com.hangxintong.common.exception.SystemErrorCodeMark;
import com.hangxintong.common.exception.SystemException;
import com.hangxintong.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Random;

@Slf4j
public class AliyunConfig {
    private static String AccessKeyID = "LTAIKX4UFmss71PM";
    private static String AccessKeySecret = "8HCqHJwFOyI23EGtqac3pUFTBbdXWI";
    //public static final String DX_SMS = "SMS_152435166";
    public static final String DX_SMS = "SMS_148710477";

    private static final String HXT_ACCESSKEY_ID = "LTAIqxVpnevm0lum";
    private static final String HXT_ACCESSKEY_SECRET = "0ooi04L0Qfbkn4BUuG7yKH2pOxhLfa";
    private static final String HXT_SIGN = "行信通";

    public static final String EXPERT_ADD_SUCCESS = "SMS_193507142";
    public static final String EXPERT_APPLY_CHECK_PASS = "SMS_193516895";
    public static final String EXPERT_APPLY_CHECK_REFUSE = "";

    @Value("${aliYun.AccessKeyID}")
    private String hxtAccessKeyID;
    @Value("${aliYun.AccessKeySecret}")
    private String hxtAccessKeySecret;
    @Value("${aliYun.Sign}")
    private String hxtSign;

    public static Result sendSms(String phone, String codeNumber) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", HXT_ACCESSKEY_ID, HXT_ACCESSKEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "行信通");
        request.putQueryParameter("TemplateCode", DX_SMS);
//        String codeNumber = AliyunConfig.getMsgCode();
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + codeNumber + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            Object code = new JSONObject(response.getData()).get("Code");
            log.info("code = {}", code);
            if (code.equals("OK")) {
                return new Result(true, StatusCode.OK, new JSONObject(response.getData()).get("Message").toString(), codeNumber);
            } else {
                return new Result(true, StatusCode.ERROR, new JSONObject(response.getData()).get("Message").toString());
            }
        } catch (ServerException e) {
            log.info("短信服务器异常：{}", e.getMessage());
            return new Result(true, StatusCode.ERROR, "短息服务器异常！");
        } catch (ClientException e) {
            log.info("短信客户端异常：{}", e.getMessage());
            return new Result(true, StatusCode.ERROR, "短息客户端异常！");
        }
    }

    /**
     * @Function: 生成验证码
     * @author: Mr.Bz
     * @Date: 2019/12/11 15:30
     */
    public static String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }


    /**
     * 发送短信通知
     *
     * @param phone
     * @param templateCode
     * @param templateParam
     * @return
     */
    public static void sendSmsText(String phone, String templateCode, String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", HXT_ACCESSKEY_ID, HXT_ACCESSKEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendBatchSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", HXT_SIGN);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);

        try {
            CommonResponse response = client.getCommonResponse(request);
            Object code = new JSONObject(response.getData()).get("Code");
            if (!code.equals("OK")) {
                throw new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST,"发送短信失败");
            }
        } catch (ServerException e) {
            log.error("发送短信异常：{}", e.getMessage(), e);
            throw new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST, "短息服务器异常！");
        } catch (ClientException e) {
            log.error("发送短信异常：{}", e.getMessage().getBytes());
            throw new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST, e.getMessage());
        }
    }

    /**
     * 发送短信通知
     *
     * @param phone
     * @param templateCode
     * @param templateParam
     * @return
     */
    public static Result  sendSmsTextNew(String phone, String templateCode, String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", HXT_ACCESSKEY_ID, HXT_ACCESSKEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", HXT_SIGN);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + templateParam + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            Object code = new JSONObject(response.getData()).get("Code");
            if (!code.equals("OK")) {
                log.error("====>{发送短信失败错误信息：}", new JSONObject(response.getData()).get("Message").toString());
                return new Result(false,StatusCode.ERROR, "发送短信失败");
            }
        } catch (ServerException e) {
            log.error("发送短信异常：{}", e.getMessage(), e);
            return new Result(false,StatusCode.ERROR, "短息服务器异常！");
        } catch (ClientException e) {
            log.error("发送短信异常：{}", e.getMessage().getBytes());
            throw new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST, e.getMessage());
        }
        return  Result.ok();
    }
    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2021/1/26 10:23
    * 阿里云批量发短信
    */
    public static Result SendBatchSms(List<String> PhoneNumberJson,List<String> SignNameJson,String TemplateCode,List<String> TemplateParamJson) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", HXT_ACCESSKEY_ID, HXT_ACCESSKEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendBatchSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //添加手机号及内容
        request.putQueryParameter("PhoneNumberJson", JSON.toJSONString(PhoneNumberJson));
        request.putQueryParameter("SignNameJson", JSON.toJSONString(PhoneNumberJson));//"[\"保险与担保网\",\"保险与担保网\"]"
        request.putQueryParameter("TemplateCode", TemplateCode);//"SMS_148710480"
        request.putQueryParameter("TemplateParamJson", JSON.toJSONString(PhoneNumberJson));//TemplateParamJson

        log.error("======>{}",request);
        try {
            CommonResponse response = client.getCommonResponse(request);
            Object code = new JSONObject(response.getData()).get("Code");
            if (!code.equals("OK")) {
                log.error("====>{发送短信失败错误信息：}", new JSONObject(response.getData()).get("Message").toString());
                return new Result(false,StatusCode.ERROR, "发送短信失败");
            }
        } catch (ServerException e) {
            log.error("发送短信异常：{}", e.getMessage(), e);
            return new Result(false,StatusCode.ERROR, "短息服务器异常！");
        } catch (ClientException e) {
            log.error("发送短信异常：{}", e.getMessage().getBytes());
            throw new SystemException(SystemErrorCodeMark.Code.DATA_NOT_EXIST, e.getMessage());
        }
        return  Result.ok();
    }

}